<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>在线考试平台</title>
    <link rel="shortcut icon" href="../images/exam.png" type="image/x-icon">
    <link rel="stylesheet" href="../css/font.css">
    <link rel="stylesheet" href="../css/xadmin.css">

</head>

<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15" style="background: #f7f8fc">

        <div class="layui-col-sm12 layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <button class="layui-btn layui-btn-sm" id="add_user_batch">批量添加用户</button>
                </div>
                <div class="layui-card-body ">
                    <table class="layui-hide" id="user_list" lay-filter="user_list"></table>
                    <script type="text/html" id="barDemo">


                        {{#  if(d.a_id== 1){ }}
                        <a class="layui-btn layui-btn-xs" lay-event="edit">保存</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="up_admin">设为管理员</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="up_teacher">设为教师</a>
                        {{#  } }}
                        {{#  if(d.a_id== 2){ }}
                        <a class="layui-btn layui-btn-xs" lay-event="edit">保存</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="up_teacher">设为教师</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="up_user">设为普通用户</a>
                        {{#  } }}
                        {{#  if(d.a_id== 3){ }}
                        <a class="layui-btn layui-btn-xs" lay-event="edit">保存</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="up_user">设为普通用户</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="up_admin">设为管理员</a>
                        {{#  } }}


                    </script>
                    <script type="text/html" id="toolbarDemo">
                        <div class="layui-btn-container">
                            <button class="layui-btn layui-btn-sm" lay-event="add_user">添加用户</button>
<!--                            <input  type="file" class="layui-btn layui-btn-sm" id="add_user_batch"  multiple="multiple"/>-->
                        </div>
                    </script>
                    <script type="text/html" id="switchTpl">
                        <input type="checkbox" name="{{d.u_state}}" value="{{d.u_id}}" lay-skin="switch"
                               lay-text="启用|停用" lay-filter="stateDemo" {{d.u_state==1?'checked':''}}>
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/javascript"  src="../lib/layui/layui.js"></script>
<script type="text/javascript" src="../js/xadmin.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script>

    layui.config({
        base: '../layui_exts/'
    }).extend({
        excel: 'excel'
    }).use(['element', "form", 'jquery', 'layer', 'table','excel','upload'], function () {
        const form = layui.form;
        const $ = layui.jquery;
        const layer = layui.layer;
        const element = layui.element;
        const table = layui.table;
        const excel = layui.excel;
        const upload = layui.upload;
        get_all_user();


        // $('#add_user_batch').change(function (e) {
        //     // 注意：这里直接引用 e.target.files 会导致 FileList 对象在读取之前变化，导致无法弹出文件
        //     var files = Object.values(e.target.files)
        //     uploadExcel(files)
        //     // 变更完清空，否则选择同一个文件不触发此事件
        //     e.target.value = ''
        // })

        let uploadInst = upload.render({
            elem: '#add_user_batch' //绑定元素
            , url: '/upload/' //上传接口（PS:这里不用传递整个 excel）
            , auto: false //选择文件后不自动上传
            , accept: 'file'
            , choose: function (obj) {// 选择文件回调
                let files = obj.pushFile()
                let fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下

                // 用完就清理掉，避免多次选中相同文件时出现问题
                for (let index in files) {
                    if (files.hasOwnProperty(index)) {
                        delete files[index]
                    }
                }
                $('#add_user_batch').next().val('');
                uploadExcel(fileArr) // 如果只需要最新选择的文件，可以这样写： uploadExcel([files.pop()])
            }
        });

    });

    function uploadExcel(files) {
        layui.use(['excel', 'layer','laytpl','table'], function () {
            let excel = layui.excel
            let layer = layui.layer
            let laytpl = layui.laytpl
            let table = layui.table
            try {
                excel.importExcel(files, {
                    // 读取数据的同时梳理数据
                    fields: {
                         'u_sno': 'B'
                        , 'u_name': 'C'
                    }
                }, function (data) {
                    let new_data
                    if (data[0].sheet1===undefined){
                        new_data=data[0].Sheet1.splice(1)
                    }else {
                        new_data=data[0].sheet1.splice(1)
                    }

                    let text = "<blockquote class=\"layui-elem-quote\">系统自动过滤已存在用户，已存在用户不被导入<span style='color: red'>共"+new_data.length+"条数据</span></blockquote>"
                    text += "<table class=\"layui-table\" style='width: 90%;margin: auto'>  " +
                        "<thead>" +
                        "    <tr>" +
                        "      <th>用户号</th>" +
                        "      <th>用户名</th>" +
                        "    </tr> " +
                        "</thead>" +
                        "<tbody>"
                    for (let i = 0; i < new_data.length; i++) {
                        text+="<tr>"
                        text+="<td>"+new_data[i].u_sno+"</td>"
                        text+="<td>"+new_data[i].u_name+"</td>"
                        text+="</tr>"
                    }
                    text+="  </tbody>" +
                        "</table>"
                    layer.open({
                        type: 1,
                        title: "待添加列表",
                        closeBtn: 1,
                        shadeClose: true,
                        btn: '确定导入',
                        yes: function (index, layero) {
                            $.ajax({
                                url: 'add_user_batch',
                                dataType: "json",//数据格式
                                type: "post",//请求方式
                                cache: false,
                                data: {
                                    userList:JSON.stringify(new_data)
                                },
                                success: function (data) {
                                    if (data.code === 200) {
                                        layer.msg(data.message, {icon: 6}, function () {
                                            layer.close(index);
                                            table.reload('user_list', {})
                                        });
                                    } else {
                                        layer.msg(data.message, {icon: 5, time: 1000});
                                    }
                                },
                                error: function (e) {
                                    alert("出现错误！！");
                                }
                            });
                        },
                        area: ['800px', '500px'],
                        content: text
                    })
                })
            } catch (e) {
                layer.alert(e.message)
            }
        })
    }

    function get_all_user() {
        const user_json = JSON.parse(sessionStorage.getItem("userJson"));


        layui.use(["form", 'jquery', 'layer', 'table'], function () {
            const $ = layui.jquery;
            const layer = layui.layer;
            const table = layui.table;
            const form = layui.form;
            table.render({
                elem: '#user_list'
                , url: 'get_all_user1'
                , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                , title: '用户表'
                , cols: [[
                    {field: 'u_id', title: '用户编号', sort: true}
                    , {field: 'u_sno', title: '用户号', edit: "text"}
                    , {field: 'u_name', title: '用户名', edit: "text"}
                    , {field: 'u_psw', title: '用户密码', edit: "text"}
                    , {field: 'u_state', title: '用户状态', templet: '#switchTpl'}
                    , {
                        field: 'a_authority',
                        title: '用户角色',
                        templet: '<div>{{d.sysAuthority.a_authority}}</div>'
                    }
                    , {title: '操作', align: 'center', toolbar: '#barDemo'}
                ]]
                , page: {				//分页设置
                    limit: 10,		//默认每一页显示数量
                    limits: [5, 10, 20, 30, 40, 50]		//可选择每页显示的数量
                }
                , parseData: function (res) { //res 即为原始返回的数据
                    var current_pages;
                    //第一次显示的时候this.page=true，把这种情况单独列出
                    if (this.page === true) current_pages = 1;
                    else current_pages = this.page.curr;
                    //根据分页要求选出需要显示的数据
                    let data = res.result.slice(this.limit * (current_pages - 1), this.limit * current_pages);
                    // alert(JSON.stringify(data));
                    return {
                        "code": res.code,
                        "msg": res.message,
                        "count": res.result.length,
                        "data": data
                    }
                }
            });

            //监听性别操作
            form.on('switch(stateDemo)', function (obj) {
                if (user_json.u_id === Number(this.value)) {
                    layer.msg("不可操作当前登录用户", {icon: 5}, function () {
                        table.reload('user_list', {})
                    });
                    return false
                }
                $.ajax({
                    url: 'update_user_state_by_u_id',
                    dataType: "json",//数据格式
                    type: "post",//请求方式
                    async: false,//是否异步请求
                    data: {
                        u_id: Number(this.value),
                        u_state: Number(this.name)
                    },
                    success: function (data) {
                        if (data.code === 200) {
                            layer.msg(data.message, {icon: 6});
                        } else {
                            layer.msg(data.message, {icon: 5, time: 1000});
                        }
                    },
                    error: function (e) {
                        alert("出现错误！！");
                    }
                });
            });


            //监听行工具事件
            table.on('tool(user_list)', function (obj) {
                let data = obj.data;
                if (user_json.u_id === data.u_id) {
                    layer.msg("不可操作当前登录用户", {icon: 5}, function () {
                        table.reload('user_list', {})
                    });
                    return false
                }
                if (obj.event === 'edit') {
                    layer.confirm('确定要对用户编号' + JSON.stringify(data.u_id) + '的修改进行保存吗？', {icon: 0}, function () {
                            $.ajax({
                                url: 'update_user_by_u_id',
                                dataType: "json",//数据格式
                                type: "post",//请求方式
                                async: false,//是否异步请求
                                data: {
                                    u_id: data.u_id,
                                    u_sno: data.u_sno,
                                    u_name: data.u_name,
                                    u_psw: data.u_psw
                                },
                                success: function (data) {
                                    if (data.code === 200) {
                                        layer.msg(data.message, {icon: 6, time: 1000}, function () {
                                            table.reload('user_list', {})
                                        });
                                    } else {
                                        layer.msg(data.message, {icon: 5, time: 1000});
                                    }
                                },
                                error: function (e) {
                                    alert("出现错误！！");
                                }
                            });

                    });
                } else if (obj.event === 'up_admin') {
                    layer.confirm('确认将此用户设为管理员？', {icon: 0}, function () {
                        $.ajax({
                            url: 'update_user_role_by_u_id',
                            dataType: "json",//数据格式
                            type: "post",//请求方式
                            async: false,//是否异步请求
                            data: {
                                u_id: data.u_id,
                                a_id: 2
                            },
                            success: function (data) {
                                if (data.code === 200) {
                                    layer.msg(data.message, {icon: 6, time: 1000}, function () {
                                        table.reload('user_list', {})
                                    });
                                } else {
                                    layer.msg(data.message, {icon: 5, time: 1000});
                                }
                            },
                            error: function (e) {
                                alert("出现错误！！");
                            }
                        });
                    });
                } else if (obj.event === 'up_user') {
                    layer.confirm('确认将此用户设为普通用户？', {icon: 0}, function () {
                        $.ajax({
                            url: 'update_user_role_by_u_id',
                            dataType: "json",//数据格式
                            type: "post",//请求方式
                            async: false,//是否异步请求
                            data: {
                                u_id: data.u_id,
                                a_id: 1
                            },
                            success: function (data) {
                                if (data.code === 200) {
                                    layer.msg(data.message, {icon: 6, time: 1000}, function () {
                                        table.reload('user_list', {})
                                    });
                                } else {
                                    layer.msg(data.message, {icon: 5, time: 1000});
                                }
                            },
                            error: function (e) {
                                alert("出现错误！！");
                            }
                        });
                    });
                } else if (obj.event === 'up_teacher') {
                    layer.confirm('确认将此用户设为教师？', {icon: 0}, function () {
                        $.ajax({
                            url: 'update_user_role_by_u_id',
                            dataType: "json",//数据格式
                            type: "post",//请求方式
                            async: false,//是否异步请求
                            data: {
                                u_id: data.u_id,
                                a_id: 3
                            },
                            success: function (data) {
                                if (data.code === 200) {
                                    layer.msg(data.message, {icon: 6, time: 1000}, function () {
                                        table.reload('user_list', {})
                                    });
                                } else {
                                    layer.msg(data.message, {icon: 5, time: 1000});
                                }
                            },
                            error: function (e) {
                                alert("出现错误！！");
                            }
                        });
                    });
                }
            });

            table.on('toolbar(user_list)', function (obj) {
                if (obj.event === 'add_user') {
                    var text = "<form class=\"layui-form layui-form-pane\" action=\"\">" +
                        "    <div class=\"layui-form-item\">" +
                        "        <label class=\"layui-form-label\">用户号</label>" +
                        "        <div class=\"layui-input-block\">" +
                        "            <input type=\"text\" name=\"u_sno\" id='u_sno' autocomplete=\"off\" placeholder=\"请输入用户号\"" +
                        "                   class=\"layui-input\">" +
                        "        </div>" +
                        "    </div>" +
                        "    <div class=\"layui-form-item\">" +
                        "        <label class=\"layui-form-label\">用户名</label>" +
                        "        <div class=\"layui-input-block\">" +
                        "            <input type=\"text\" name=\"u_name\" id='u_name' autocomplete=\"off\" placeholder=\"请输入用户名\"" +
                        "                   class=\"layui-input\">" +
                        "        </div>" +
                        "    </div>" +
                        "    <div class=\"layui-form-item\">" +
                        "        <label class=\"layui-form-label\">密码</label>" +
                        "        <div class=\"layui-input-block\">" +
                        "            <input type=\"password\" name=\"u_psw\" id='u_psw' autocomplete=\"off\" placeholder=\"请输入密码\"" +
                        "                   class=\"layui-input\">" +
                        "        </div>" +
                        "    </div>" +
                        "    <div class=\"layui-form-item\">" +
                        "        <label class=\"layui-form-label\">确认密码</label>" +
                        "        <div class=\"layui-input-block\">" +
                        "            <input type=\"password\" name=\"re_psw\" id='re_psw' autocomplete=\"off\" placeholder=\"请输入确认密码\"" +
                        "                   class=\"layui-input\">" +
                        "        </div>" +
                        "    </div>" +
                        "</form>"
                    var index = layer.open({
                        type: 1,
                        title: "添加用户",
                        closeBtn: 1,
                        shadeClose: true,
                        btn: '确定',
                        yes: function (index, layero) {
                            var u_sno = $("#u_sno").val();
                            var u_name = $("#u_name").val();
                            var u_psw = $("#u_psw").val();
                            var re_psw = $("#re_psw").val();
                            if (u_psw !== re_psw) {
                                layer.msg("两次密码不一致", {icon: 5, time: 1000});
                                return false;
                            }
                            $.ajax({
                                url: 'add_user',
                                dataType: "json",//数据格式
                                type: "post",//请求方式
                                cache: false,
                                data: {
                                    u_sno: u_sno,
                                    u_name: u_name,
                                    u_psw: u_psw
                                },
                                success: function (data) {
                                    if (data.code === 200) {
                                        layer.msg(data.message, {icon: 6}, function () {
                                            layer.close(index);
                                            table.reload('user_list', {})
                                        });
                                    } else {
                                        layer.msg(data.message, {icon: 5, time: 1000});
                                    }
                                },
                                error: function (e) {
                                    alert("出现错误！！");
                                }
                            });
                        },
                        area: ['500px', '400px'],
                        content: text
                    });
                }
            });

        });
    }

    function getDateDiff(dateTimeStamp) {
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - dateTimeStamp;
        if (diffValue < 0) {
            //若日期不符则弹出窗口告之
            //alert("结束日期不能小于开始日期！");
        }
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;
        if (monthC >= 1) {
            result = "创建于" + parseInt(monthC) + "个月前";
        } else if (weekC >= 1) {
            result = "创建于" + parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            result = "创建于" + parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            result = "创建于" + parseInt(hourC) + "个小时前";
        } else if (minC >= 1) {
            result = "创建于" + parseInt(minC) + "分钟前";
        } else
            result = "刚刚创建";
        return result;
    }

    //js函数代码：字符串转换为时间戳
    function getDateTimeStamp(dateStr) {
        var time_stamp = Date.parse(dateStr.replace(/-/gi, "/"));
        return getDateDiff(time_stamp)
    }
</script>
<!--<script type="text/html" id="LAY-excel-export-ans">-->
<!--    {{# layui.each(d.data, function(file_index, item){ }}-->
<!--    <blockquote class="layui-elem-quote">{{d.files[file_index].name}}</blockquote>-->
<!--    <div class="layui-tab">-->
<!--        <div class="layui-tab-content">-->
<!--            {{# layui.each(item, function(sheet_name, content) { }}-->
<!--            <div class="layui-tab-item">-->
<!--                <table class="layui-table">-->
<!--                    {{# layui.each(content, function(row_index, value) { }}-->
<!--                    {{# var col_index = 0 }}-->
<!--                    <tr>-->
<!--                        {{# layui.each(value, function(col_key, val) { }}-->
<!--                        <td id="table-export-{{file_index}}-{{sheet_name}}-{{row_index}}-{{col_index++}}">{{val}}</td>-->
<!--                        {{# });}}-->
<!--                    </tr>-->
<!--                    {{# });}}-->
<!--                </table>-->
<!--            </div>-->
<!--            {{# }); }}-->
<!--        </div>-->
<!--    </div>-->
<!--    {{# }) }}-->
<!--</script>-->
</html>